import styles from "./index.module.less";
import classNames from "classnames";
import { memo, useEffect, useRef, useState } from "react";
import { Button, Col, message, Checkbox } from "antd";
import type { ProFormInstance } from "@ant-design/pro-form";
import { ProForm, ProFormText } from "@ant-design/pro-form";
import { LockOutlined, MenuOutlined, UserOutlined } from "@ant-design/icons";
import { useNavigate } from "react-router-dom";
import { login } from "@/api/modules/user";
import { useRequest, useUpdateEffect } from "ahooks";
import { LoginStatus, SettingType } from "@/enums";
import useGetFakeCaptcha from "@/hooks/useGetFakeCaptcha";
import { HOME_URL } from "@/config/config";
import { useGlobalActionFunction } from "@/store/modules/global";
import { useAuthActionFunction } from "@/store/modules/auth";
import { RESULT_CODES } from "@/api/helper/ResultCode";

const Login = () => {
	const formRef = useRef<ProFormInstance>();
	const interval = useRef<any>();
	const navigate = useNavigate();
	const setToken = useGlobalActionFunction("setToken");
	const [setCurrentUser, setSettingMaps] = useAuthActionFunction(["setCurrentUser", "setSettingMaps"]);
	
	// 记住密码状态
	const [rememberPassword, setRememberPassword] = useState(false);

	const {
		src,
		captchaToken,
		run: getFakeCaptchaRun
	} = useGetFakeCaptcha({
		onSuccess: (e: any) => {
			if (e && !interval.current) {
				interval.current = setInterval(() => {
					getFakeCaptchaRun().then();
				}, 60 * 1000);
			}
		}
	});

	const { loading, run } = useRequest(login, {
		manual: true,
		onSuccess: async (data, params) => {
			// 错误的情况
			if (false) {
				formRef.current?.setFields([
					{
						name: "password",
						value: params?.[0]?.password,
						errors: ["密码错误" as string]
					}
				]);
				return;
			}

			// 判断验证码错误的情况
			if (false) {
				formRef.current?.setFields([
					{
						name: "captcha",
						value: undefined,
						errors: [data?.msg as string]
					}
				]);
				getFakeCaptchaRun().then();
				return;
			}
			if (data.code === RESULT_CODES.SUCCESS) {
				console.log(data, '<=========data')
				// 想cookie中存储token
				setToken(data?.data?.tokenInfo?.tokenValue ?? "");

				setCurrentUser({
					userName: params?.[0]?.account
				});

				setSettingMaps({
					type: SettingType.GOODS_STATUS_LABEL
				});

				// 如果勾选了记住密码，保存用户名和密码到localStorage
				if (rememberPassword) {
					localStorage.setItem('savedAccount', params?.[0]?.account || '');
					localStorage.setItem('savedPassword', params?.[0]?.password || '');
					localStorage.setItem('rememberPassword', 'true');
				}

				message.success("登录成功");
				return navigate(HOME_URL);
			}
		}
	});

	//清除验证码定时器
	useEffect(() => {
		// 页面加载时检查是否有保存的用户名和密码
		const savedAccount = localStorage.getItem('savedAccount');
		const savedPassword = localStorage.getItem('savedPassword');
		const isRemembered = localStorage.getItem('rememberPassword') === 'true';
		
		if (isRemembered && savedAccount && savedPassword) {
			setRememberPassword(true);
			formRef.current?.setFieldsValue({
				account: savedAccount,
				password: savedPassword
			});
		}
		
		return () => {
			if (interval.current) {
				clearInterval(interval.current);
			}
		};
	}, []);

	/**
	 * 提交表单
	 */
	const onSubmit = (values: any) => {
		let data = {
			...values,
			loginType:"username",
			captchaToken
		};

		run(data);
		return Promise.resolve(true);
	};

	const handleRemember = (e: any) => {
		const isChecked = e.target.checked;
		setRememberPassword(isChecked);
		
		// 如果取消勾选，清除localStorage中保存的数据
		if (!isChecked) {
			localStorage.removeItem('savedAccount');
			localStorage.removeItem('savedPassword');
			localStorage.removeItem('rememberPassword');
		}
	}

	return (
		<div className={styles.container}>
			<div className={styles.bg}>
				<div className={styles.login_flex}>
					<div className={styles.left_image}></div>
					<div className={styles.login_container}>
						<div className={styles.title}>欢迎登录</div>
						<div className={styles.subtitle}>大成运和智能调度平台</div>
						<ProForm submitter={false} formRef={formRef} onFinish={onSubmit}>
							<>
								<ProFormText
									name="account"
									fieldProps={{
										size: "large"
									}}
									label={'用户名'}
									placeholder={"请输入用户名/邮箱/账号"}
									rules={[
										{
											required: true,
											message: "请输入用户名/邮箱/账号"
										}
									]}
								/>

								<ProFormText.Password
									name="password"
									fieldProps={{
										size: "large"
									}}
									label={'密码'}
									placeholder={"请输入账户密码"}
									rules={[
										{
											required: true,
											message: "请输入账户密码"
										}
									]}
								/>
							</>
							<Checkbox checked={rememberPassword} onChange={handleRemember}>记住密码</Checkbox>

							<Button size="large" loading={loading} htmlType={"submit"} className={styles.button} type={"primary"}>
								登录
							</Button>
							<div className={styles.btn_forget}>忘记密码?</div>
						</ProForm>
					</div>
				</div>
			</div>
		</div>
	);
};
export default memo(Login);
